package com.mydemo.common.utils;

import com.mydemo.common.Constant;
import com.mydemo.common.exception.user.UserException;
import com.mydemo.common.pojo.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * JWT工具类
 *
 * @author Last_Island
 * @version 1.0
 */
public class JWTUtils {

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    @Autowired
    private RedisUtils redisUtils;

    public String createToken(LoginUser loginUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("user", loginUser.getUsername());
        return createToken(claims);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        return Jwts.builder()
                .setClaims(claims)
//                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从token中获取JWT中的信息
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
//            LOGGER.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expireTime * 60 * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = (String) claims.get("user");
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 通过token从缓存中获取登录用户
     */
    public LoginUser getLoginUser(String token) {
        String key = Constant.SYS_USER_TOKEN + token;
        LoginUser cacheObject = redisUtils.getCacheObject(key);
        if (cacheObject == null){
            throw new UserException("token已失效，请重新登录");
        }
        redisUtils.expire(key, expireTime, TimeUnit.MINUTES);
        return cacheObject;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        if (expiredDate == null)
            return false;
        return expiredDate.before(new Date());
    }

    /**
     * 判断token是否在redis中
     * @param username
     * @param token
     * @return
     */
    private boolean isTokenInRedis(String username,String token){
        String key = Constant.SYS_USER_TOKEN + username;
        if (redisUtils.getCacheObject(key).equals(token)){
            redisUtils.expire(key, expireTime, TimeUnit.MINUTES);
            return true;
        }
        return false;
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }
}
